#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json

from bottle import Bottle
from bottle import request, response

from mqtt.MqttService import MqttService

mqttAdm = Bottle()


@mqttAdm.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@mqttAdm.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


# 微品mqtt服务
# Vue+ele管理台界面数据接口
# 172.17.0.9:9006/mqtt/listen?deviceId=ESP826608F9E05D303F  {"device_id": "ESP826608F9E05D303F","status":1}
# 172.17.0.9:9006/mqtt/loadDeviceTopic?deviceId=ESP826608F9E05D303F {"temperature":"37.5","humidity":"57"}
class MqttAdminRoute:
    json_data_file = ""
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
    }

    def __init__(self):
        return

    # -- 管理台工具类查询
    @staticmethod
    @mqttAdm.get('/fetchDevice')
    def fetch_device():
        # 从redis中获取设备列表
        datas = MqttService.fetch_device()
        views = {"list": datas}
        return {'code': 200, 'data': views, 'message': ''}

    # -- 管理台工具类查询
    @staticmethod
    @mqttAdm.get('/listen')
    def listen_device():
        flg = MqttService.listen_device(request.params.deviceId)
        if flg:
            return {'code': 200, 'data': flg, 'message': 'iot设备读取成功'}
        else:
            return {'code': 500, 'data': flg, 'message': 'iot设备读取失败'}

    @staticmethod
    @mqttAdm.get('/load')
    def listen_device():
        try:
            device_data = MqttService.load_topic(request.params.deviceId)
            view_list = [MqttAdminRoute.chg_listen_data(_data) for _data in device_data]
            view_data = json.dumps(view_list, ensure_ascii=False)
            pie_roles_data = MqttAdminRoute.chg2pieCol(view_data)
            return {'code': 200, 'data': view_data, 'message': ''}
        except Exception as e:
            return {'code': 500, 'data': {}, 'message': MqttAdminRoute.ERROR_CODE["80"]}

    @staticmethod
    def chg_listen_data(bytes):
        return json.loads(str(bytes).replace("\'", "").replace("b{", "{"))

    def chg2pieCol(datas, keys):
        i = 0
        pie_sets = []
        while (i < len(keys)):
            i += 1
            sub_pop = []
            for data in datas:
                sub_pop.append(data[keys[i]])
            sub_pop_name = keys[i]
            pie_sets.append({sub_pop_name: sub_pop})
        return pie_sets;
